package com.mrx.java8.stream.parallel;

import org.junit.jupiter.api.Test;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

/**
 * @author XH.M
 * @description
 * @create 2018-12-01 17:25
 */
public class TestForkJoin {

    /**
     * 100000000L    34ms
     * 10000000000L  1512ms
     * 100000000000L 15790ms
     */
    @Test
    public void test1(){
        Instant start = Instant.now();

        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinTask<Long> task = new ForkJoinCalculate(0,100000000000L);
        Long sum = pool.invoke(task);
        System.out.println(sum);

        Instant end = Instant.now();
        System.out.println("耗时: "+Duration.between(start,end).toMillis());
    }

    /**
     * 100000000L    29ms
     * 10000000000L  2685ms
     * 100000000000L 26559ms
     */
    @Test
    public void test2(){
        Instant start = Instant.now();
        long sum = 0;
        for(long i=0;i<=100000000000L;i++){
            sum += i;
        }
        System.out.println(sum);

        Instant end = Instant.now();
        System.out.println("耗时: "+Duration.between(start,end).toMillis());
    }

    /**
     * java8 串行流
     * 100000000000L   36821ms
     */
    @Test
    public void test3(){
        Instant start = Instant.now();

        Long sum = LongStream.rangeClosed(1,100000000000L)
                .reduce(0,Long::sum);
        System.out.println(sum);

        Instant end = Instant.now();
        System.out.println("耗时: "+Duration.between(start,end).toMillis());
    }


    /**
     * java8并行流
     * 100000000000L 8533ms
     */

    @Test
    public void test4(){
        Instant start = Instant.now();

        Long sum = LongStream.rangeClosed(1,100000000000L)
                .parallel()
                .reduce(0,Long::sum);
        System.out.println(sum);

        Instant end = Instant.now();
        System.out.println("耗时: "+Duration.between(start,end).toMillis());
    }
}
